# -*- coding: utf-8 -*-

import os
import logging

# 以下只适用于windows系统，必须安装office或wps
# pip install pywin32
import pythoncom
from win32com import client

from py_win import py_dir_path


def excel_export_image(excel_path, sheet_list, image_dir, image_type):
    """
    导出excel中所有的chart为图片，图片以sheet页命名
    每个sheet只有一张chart图
    :param excel_path:
    :param sheet_list:
    :param image_dir:保存图片的文件夹
    :param image_type:
    :return:
    """
    try:
        pythoncom.CoInitialize()
        excel = client.DispatchEx("excel.application")
        workbook = excel.Workbooks.Open(excel_path)

        for sheet_name in sheet_list:
            sheet = workbook.Worksheets(sheet_name)
            for chart in sheet.ChartObjects():
                image_name = sheet_name + '.' + image_type
                image_path = os.path.join(image_dir, image_name)
                chart.Chart.Export(image_path, image_type)
                pass
            pass

        workbook.Close(False)
        excel.Quit()
        pythoncom.CoUninitialize()
        pass
    except Exception as e:
        logging.exception(e)
        return False
    pass


if __name__ == '__main__':
    # 使用绝对路径
    word_path = os.path.join(py_dir_path, 'word.docx')
    pdf_path = os.path.join(py_dir_path, 'pdf.pdf')
    flag = word_export_pdf(word_path, pdf_path)

    pass
